/**
 * Created by hy on 2017/3/10.
 */
const state = {
  /**
   * [
   *    {
   *      keyword: '',
   *      counter: 1,
   *      lastUpdateTime: 1111111111111
   *    }
   * ]
   */
  searchHistory: JSON.parse(window.localStorage.getItem('search_history')) || []
}

const mutations = {
  UPDATE_SEARCH_HISTORY (state, history) {
    state.searchHistory = history
    window.localStorage.setItem('search_history', JSON.stringify(history))
  }
}
const getters = {
  searchHistory (state) {
    return state.searchHistory.sort((a, b) => a.lastUpdateTime < b.lastUpdateTime)
  }
}
const actions = {
  newSearchHistory (context, payload) {
    console.log(context, payload)
    let list = [...context.state.searchHistory]
    const keywordIndex = list.map(i => i.keyword).indexOf(payload)
    if (list.length > 0 && keywordIndex >= 0) {
      list[keywordIndex].counter++
      list[keywordIndex].lastUpdateTime = new Date().getTime()
    } else {
      list.push({
        keyword: payload,
        counter: 1,
        lastUpdateTime: new Date().getTime()
      })
    }
    context.commit('UPDATE_SEARCH_HISTORY', list)
  },
  clearSearchHistory (context) {
    context.commit('UPDATE_SEARCH_HISTORY', [])
  }
}
export default {
  state,
  mutations,
  getters,
  actions
}
